package com.evo.chat.web.service.impl;

import com.evo.chat.admin.repository.ReplyRepository;
import com.evo.chat.common.Result;
import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.exception.ChatException;
import com.evo.chat.common.utils.Md5Util;
import com.evo.chat.common.utils.ResultUtil;
import com.evo.chat.web.domain.UserInfo;
import com.evo.chat.web.domain.UserPassword;
import com.evo.chat.web.domain.Words;
import com.evo.chat.web.repository.PasswordRepository;
import com.evo.chat.web.repository.UserRepository;
import com.evo.chat.web.repository.WordsRepository;
import com.evo.chat.web.service.UserService;
import com.evo.chat.web.vo.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author luwenzheng
 * date 2020-02-06
 */
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordRepository passwordRepository;

    @Autowired
    private WordsRepository wordsRepository;

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public Result findAll() {
        List<UserInfo> all = userRepository.findAll();
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            userInfoVOList.add(convertFromModel(all.get(i)));
        }
        return ResultUtil.success(userInfoVOList);
    }

    /**
     * 创建用户
     */
    @Override
    public Result createUser(String name, String age, String password) {
        UserInfo userInfo = userRepository.findByName(name);
        if (userInfo != null) {
            return ResultUtil.error(ResultEnum.USER_HAS_EXIST);
        }
        userInfo = new UserInfo();
        userInfo.setName(name);
        userInfo.setAge(age);
        UserPassword userPassword = new UserPassword();
        userPassword.setUser(userInfo);
        try {
            userPassword.setEncryptPassword(Md5Util.EncodeByMd5(password));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
        passwordRepository.save(userPassword);
        return ResultUtil.success(convertFromModel(userRepository.save(userInfo)));
    }

    @Override
    public UserInfo login(String name, String encryptPassword) {
        //通过用户的手机获取用户对象
        UserInfo userDO = userRepository.findByName(name);
        if(userDO == null){
            throw new ChatException(ResultEnum.USER_NOT_EXIST);
        }
        UserPassword userPasswordDO = passwordRepository.findByUserId(userDO.getId());
        if(!encryptPassword.equals(userPasswordDO.getEncryptPassword())){
            throw new ChatException(ResultEnum.USER_PASSWORD_ERROR);
        }
        return userDO;
    }

    @Override
    @Transactional
    public Result delUser(String name) {
        //通过用户的手机获取用户对象
        UserInfo userInfo = userRepository.findByName(name);
        if(userInfo == null){
            throw new ChatException(ResultEnum.USER_NOT_EXIST);
        }
        UserPassword byUserId = passwordRepository.findByUserId(userInfo.getId());

        List<Words> words = wordsRepository.findByUserId(byUserId.getId());
        System.out.println("size=> " + words.size());
        for (int i = 0; i < words.size(); i++) {
            //删除留言关联的回复表
//            replyRepository.deleteByWordsId(words.get(i).getId());
            //删除留言表
            wordsRepository.deleteById(byUserId.getId());
        }
        passwordRepository.deleteById(byUserId.getId());
        userRepository.deleteById(userInfo.getId());
        return ResultUtil.success();
    }

    @Override
    public Result banned(String name) {
        //通过用户的手机获取用户对象
        UserInfo userInfo = userRepository.findByName(name);
        if(userInfo == null){
            throw new ChatException(ResultEnum.USER_NOT_EXIST);
        }
        userInfo.setAllowWords(false);
        userRepository.save(userInfo);
        return ResultUtil.success();
    }


    /**
     * 转换实体
     * @param userModel
     * @return
     */
    private UserInfoVO convertFromModel(UserInfo userModel){
        if(userModel == null){
            return null;
        }
        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }
}
